<template>
  <div class="superInviter">
    <!-- 邀请 -->
    <div class="head_box">
      <!-- <div class="tipBox">
				<p v-if="dataForm.status == 1">
					当前账户合作中商户
					<strong>{{ dataForm.cooperativeBusinessNum }}</strong>
					家，邀请未处理商户
					<strong>{{ dataForm.pendingBusinessNum }}</strong>
					家，剩余可邀请
					<strong>{{ dataForm.remainingBusinessNum }}</strong>
					家商户。有效期至：{{ dataForm.validityPeriod }}
				</p>
				<p v-if="dataForm.status == 2">当前超级会员插件已过期，为了不影响您的使用请尽快购买。</p>
				<span @click="superDetail">{{ dataForm.status == 1 && dataForm.remainingBusinessNum > 0 ? '详情' : '立即购买' }}</span>
			</div> -->

      <div v-if="butieData >= 0 && butieData != null" class="tipBox">
        <p>
          <span>{{ butieStatus ? "已开通" : "未开通" }}
            <el-tooltip
              class="item"
              effect="dark"
              :content="butieStatusText"
              placement="top"
            >
              <i class="el-icon-question" />
            </el-tooltip>
          </span>
          当前补贴账号余额为
          <strong>{{ butieData }}</strong>
          元
        </p>
        <span @click="butieDetail">{{
          butieData > 0 ? "详情" : "立即充值"
        }}</span>
      </div>
    </div>

    <!-- 状态 -->
    <div class="inquire_box">
      <div class="status_list">
        <div
          v-for="(item, index) in status_list"
          :key="index"
          class="li"
          :style="{ color: statusIndex == index ? '#ffb72f' : '' }"
          @click="statusBtn(index)"
        >
          {{ item.txt }}
        </div>
      </div>

      <div class="serch_box">
        <el-input v-model="conditions.merchName" placeholder="请输入商户名称" />
        <el-input
          v-model="conditions.merchPhone"
          placeholder="请输入联系电话"
        />
        <el-select v-model="conditions.stakeValue" placeholder="请选择出资方">
          <el-option
            v-for="item in conditions.stake"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button type="primary" @click="serchBtn">搜索</el-button>
        <el-button type="primary" @click="resetBtn">重置</el-button>
      </div>
    </div>

    <!-- 规则提示 -->
    <div v-if="statusIndex == 0" class="tipRule">
      <div class="top-tips app-main-tips-box">
        <div class="title">
          <i class="el-icon-warning" />
          说明
        </div>
        <ul>
          <li>
            1.修改的折扣/抽佣比例商户未同意前，列表原折扣/比例下将显示修改信息，用户下单享受原折扣优惠，抽取原比例佣金
          </li>
          <li>
            2.商户同意修改后，列表将按照修改后折扣/比例显示，用户下单享受新折扣优惠，并按照新比例抽佣
          </li>
          <li>
            3.商户拒绝修改后，列表将按照修改前折扣/比例显示，用户下单享受原折扣优惠，并按照原比例抽佣
          </li>
          <li>
            4.出资方为本商户且不需要合作商户确定，修改内容不需要合作商户确定
          </li>
        </ul>
      </div>
    </div>

    <!-- 表格 -->
    <div v-loading="loading" class="table_box">
      <el-table
        :data="tableData"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        border
        style="width: 100%"
      >
        <el-table-column prop="merchName" label="商户名称" />
        <el-table-column prop="merchPhone" label="联系电话" />
        <el-table-column prop="address" label="商户总部地址" />
        <el-table-column prop="stakeValue" label="出资方">
          <template slot="header" slot-scope="scope">
            <span>出资方</span>
            <el-tooltip
              popper-class="el-tooltip-theme-fresh"
              placement="top"
              effect="light"
            >
              <div slot="content">出资方指优惠折扣或活动优惠的钱由谁承担</div>
              <i class="el-icon-question" />
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <p>{{ scope.row.stakeValue == 1 ? "本商户" : "合作商户" }}</p>
            <p v-if="scope.row.afterFinancingParty" style="color: red">
              {{
                scope.row.afterFinancingParty == 1
                  ? "【本商户 (待确定)】"
                  : "【合作商户 (待确定)】"
              }}
            </p>
          </template>
        </el-table-column>
        <el-table-column prop="discount" label="优惠折扣">
          <template slot-scope="scope">
            <div>{{ scope.row.discount }}折</div>
            <div
              v-if="
                scope.row.afterDiscount >= 0 && scope.row.afterDiscount != null
              "
              style="color: red"
            >
              【{{ scope.row.afterDiscount }}折 未确定】
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="commission" label="抽佣比例">
          <template slot-scope="scope">
            <div>{{ scope.row.commission }}%</div>
            <div
              v-if="
                scope.row.afterRakeRate >= 0 && scope.row.afterRakeRate != null
              "
              style="color: red"
            >
              【{{ scope.row.afterRakeRate }}% 未确定】
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="integralAwar" label="积分奖励 (1元)" />
        <el-table-column>
          <template slot="header" slot-scope="scope">
            <span>积分抵扣比例</span>
            <el-tooltip
              popper-class="el-tooltip-theme-fresh"
              placement="top"
              effect="light"
            >
              <div slot="content">
                指用户可使用积分抵扣金额比例，抵扣的钱邀请商户补贴给合作商户
              </div>
              <i class="el-icon-question" />
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <p>{{ scope.row.integralProportion }} %</p>
            <p
              v-if="
                scope.row.afterDeductionRatio >= 0 &&
                  scope.row.afterDeductionRatio != null
              "
              style="color: red"
            >
              【{{ scope.row.afterDeductionRatio }} % 未确定】
            </p>
          </template>
        </el-table-column>
        <el-table-column v-if="statusIndex == 0" prop="time" label="合作时间" />
        <el-table-column v-if="statusIndex == 0" label="操作">
          <template slot-scope="scope">
            <el-button
              :disabled="
                (scope.row.afterDiscount >= 0 &&
                  scope.row.afterDiscount != null) ||
                  (scope.row.afterRakeRate >= 0 &&
                    scope.row.afterRakeRate != null) ||
                  (scope.row.afterDeductionRatio >= 0 &&
                    scope.row.afterDeductionRatio != null) ||
                  scope.row.afterFinancingParty
                  ? true
                  : false
              "
              type="text"
              size="small"
              @click="changeDialog(scope.row)"
            >
              修改
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="cancelHz(scope.row)"
            >取消合作</el-button>
            <el-button
              type="text"
              size="small"
              @click="opeBtn(scope.row)"
            >订单信息</el-button>
          </template>
        </el-table-column>

        <el-table-column
          v-if="statusIndex == 1"
          prop="exTime"
          label="退出时间"
        />
        <el-table-column v-if="statusIndex == 1" label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              :disabled="scope.row.isInvitedAgain == 0 ? false : true"
              @click="againInvite(scope.row)"
            >再次邀请</el-button>
            <el-button
              type="text"
              size="small"
              @click="opeBtn(scope.row)"
            >订单信息</el-button>
          </template>
        </el-table-column>
        <el-table-column
          v-if="statusIndex == 1"
          prop="exParty"
          label="退出操作方"
        />
      </el-table>
    </div>

    <!-- 修改优惠信息 -->
    <el-dialog
      title="修改"
      class="changeDialog"
      :visible.sync="chengeDialogVisible"
      width="30%"
      center
    >
      <div class="inpLis">
        优惠折扣：
        <el-input v-model="preferInput" />
        折
      </div>
      <div class="inpLis">
        抽佣比例：
        <el-input v-model="mokeInput" :disabled="canCustomRate" />
        %
      </div>
      <div style="color: #ffb72f; text-align: center">
        范围 ({{ customMinRate }}% ~ {{ customMaxRate }}%)
      </div>
      <div style="color: red; text-align: center; margin-top: 16px">
        注：新折扣和抽佣比例只有商户确定后才生效
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="chengeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="trueChangeDialog">确 定</el-button>
      </span>
    </el-dialog>
    <pag-ination
      :page-total="pagTotal"
      @pageNum="getPageNum"
      @pageSize="getPageSize"
    />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import pagInation from '../pagInation/index.vue'
import {
  querySuperMemberStatus,
  queryCooperationRecord,
  modifyDiscountAndRakeRate,
  cancelCooperation,
  addBusinessToMember,
  getSuperMemberRateConfig,
  getSubsidyAccountBalance,
  isOpenSubsidyAccount
} from '@/api/business'
export default {
  components: {
    'pag-ination': pagInation
  },
  data() {
    return {
      // 商户信息
      businessId: '',

      /* 状态 */
      statusIndex: 0, // 0合作   1已退出
      status_list: [
        {
          id: 0,
          txt: '合作中'
        },
        {
          id: 1,
          txt: '已退出'
        }
      ],

      /* 查询 */
      conditions: {
        merchName: '',
        merchPhone: '',
        stake: [
          {
            value: 1,
            label: '本商户'
          },
          {
            value: 2,
            label: '合作商户'
          }
        ],
        stakeValue: '',
        pageNum: 1,
        pageSize: 10
      },
      pagTotal: null,
      loading: false,

      /* 合作状态 */
      dataForm: {
        cooperativeBusinessNum: 0,
        pendingBusinessNum: 0,
        remainingBusinessNum: 0,
        validityPeriod: '',
        status: ''
      },

      /* 补贴余额 */
      butieData: null,

      /* 表格 */
      tableData: [],
      rowConte: '',
      chengeDialogVisible: false,
      preferInput: '', // 优惠折扣
      mokeInput: '', // 抽佣比例
      canCustomRate: false, // 是否可自定义佣金比例
      customMaxRate: '',
      customMinRate: '',

      // 时间
      time: '',
      // 补贴状态
      butieStatus: 1
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    butieStatusText({ butieStatus }) {
      return butieStatus
        ? '已开通表示商户已开通补贴账号，可给合作商户补贴'
        : '未开通表示商户未开通补贴账号，不可给合作商户补贴 '
    }
  },
  mounted() {
    console.log('userInfo', this.userInfo)
    const { id } = this.userInfo.business
    this.businessId = id
    this.querySuperMemberStatusFun()
    this.getSubsidyAccountBalanceFun()
    this.cooperationFun()
    this.getButieStatus()
  },
  methods: {
    // 商户补贴状态
    async getButieStatus() {
      const { data } = await isOpenSubsidyAccount()
      console.log('商户补贴状态', data)
      this.butieStatus = data
    },
    statusBtn(index) {
      this.statusIndex = index
      this.cooperationFun()
    },

    // 插件状态
    querySuperMemberStatusFun() {
      querySuperMemberStatus().then((res) => {
        console.log('查询商户超级会员插件状态', res)
        this.dataForm = res.data
      })
    },

    // 插件状态，详情
    superDetail() {
      if (this.dataForm.status == 2) {
        // 欠费
        this.$router.push({
          name: 'PlugCenterSupRenew'
        })
      } else {
        // 购买
        this.$router.push({
          name: 'PlugCenterAddMerc'
        })
      }
    },

    // 补贴状态
    getSubsidyAccountBalanceFun() {
      getSubsidyAccountBalance({ businessId: this.businessId }).then((res) => {
        // console.log('补贴状态', res);
        if (res.code == 0 && res.data) {
          this.butieData = res.data / 100
        }
      })
    },
    butieDetail() {
      if (this.butieData) {
        // console.log('详情');
        this.$router.push({ name: 'MarketingActivitySuperInviterButie' })
      } else {
        this.$confirm(
          '当前补贴余额过低，为了不影响用户体验请尽快充值',
          '提示',
          {
            confirmButtonText: '立即充值',
            cancelButtonText: '确定',
            type: 'warning'
          }
        )
          .then(() => {
            window.open('https://dashboard.huifu.com/customers/login')
          })
          .catch(() => {})
      }
    },

    /* 条件查询 */
    serchBtn() {
      this.cooperationFun()
    },
    resetBtn() {
      this.cleanConditionsFun()
      this.cooperationFun()
    },
    // 清空条件
    cleanConditionsFun() {
      this.conditions.merchName = ''
      this.conditions.merchPhone = ''
      this.conditions.stakeValue = ''
    },
    // 获取分页
    getPageNum(val) {
      this.conditions.pageNum = val
      this.cooperationFun()
    },
    getPageSize(val) {
      this.conditions.pageSize = val
      this.cooperationFun()
    },

    /* 表格 */
    opeBtn(row) {
      this.rowConten = row
      this.$router.push({
        name: 'MarketingActivitySuperInviterOrderMsg',
        query: {
          merchOption: JSON.stringify(this.rowConten)
        }
      })
    },
    // 再次邀请
    againInvite(row) {
      this.rowConten = row
      if (this.dataForm.status == 1 && this.dataForm.remainingBusinessNum > 0) {
        // 已开通状态，将跳转收费界面
        this.$router.push({
          name: 'MarketingActivitySuperInviterMerch',
          query: {
            merchOption: JSON.stringify(this.rowConten)
          }
        })
      } else if (this.dataForm.status == 2) {
        // 欠费状态，将跳转收费界面
        this.$router.push({
          name: 'PlugCenterSupRenew'
        })
      } else if (this.dataForm.remainingBusinessNum == 0) {
        this.$confirm('邀请商户数已使用完，请购买后操作', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.$router.push({
              name: 'PlugCenterAddMerc'
            })
          })
          .catch(() => {})
      }
    },
    // 修改
    changeDialog(row) {
      // this.chengeDialogVisible = true; //弹窗改为跳转页面20220622
      this.$router.push({
        name: 'MarketingActivitySuperInviterEditMerch',
        query: {
          operType: 'change',
          rowId: row.id
        }
      })

      this.rowConten = row
      const { discount, commission } = this.rowConten
      this.preferInput = discount
      this.mokeInput = commission
      this.getMokeFun()
    },
    trueChangeDialog() {
      this.chengeDialogVisible = false
      if (this.canCustomRate == false) {
        if (
          this.mokeInput <= this.customMaxRate &&
          this.mokeInput >= this.customMinRate
        ) {
          this.changeDisRak()
        }
      }
    },
    // 取消合作
    cancelHz(row) {
      this.rowConten = row
      this.$confirm(
        '是否取消合作？取消后用户在当前商家消费将不享受超级会员折扣，请谨慎操作。',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.cancelCooperationFun()
        })
        .catch(() => {})
    },

    // 抽佣比例
    getMokeFun() {
      const businessId = this.businessId
      getSuperMemberRateConfig({ businessId }).then((res) => {
        console.log('抽佣比例', res)
        const { canCustomRate, customMaxRate, customMinRate } = res.data
        if (canCustomRate == 1) {
          this.canCustomRate = false
        } else {
          this.canCustomRate = true
        }
        this.customMaxRate = customMaxRate
        this.customMinRate = customMinRate
      })
    },
    // 请求合作列表
    cooperationFun() {
      const from = {
        businessName: this.conditions.merchName,
        cooperate: this.statusIndex == 0 ? 1 : 0, // 0：已退出, 1：合作中
        mobile: this.conditions.merchPhone,
        financingParty: this.conditions.stakeValue,
        pageNum: this.conditions.pageNum,
        pageSize: this.conditions.pageSize
      }
      console.log(from)
      queryCooperationRecord(from).then((res) => {
        console.log('请求合作列表', res)
        if (res.code == 0) {
          this.pagTotal = res.data.total
          const data = res.data.list
          const tableData = []
          data.forEach((el) => {
            const dataItem = {
              merchName: el.joinBusinessName,
              merchPhone: el.joinMobilePhone,
              address: el.joinAddress,
              stakeValue: el.financingParty,
              afterFinancingParty: el.afterFinancingParty,
              afterDeductionRatio: el.afterDeductionRatio,
              needAgree: el.needAgree,

              discount: el.discount,
              commission: el.rakeRate,

              afterDiscount: el.afterDiscount,
              afterRakeRate: el.afterRakeRate,

              integralAwar: el.rewardCoefficient,
              recyclePoints: el.recyclePoints,
              integralProportion: el.deductionRatio,

              time: el.inviteTime,
              id: el.id,
              status: el.status, // == 0 ? '已退出' : '合作中'
              exTime: el.exitTime,
              exParty: el.exitType == 1 ? '本商户取消合作' : '参与者取消合作',
              exitType: el.exitType, // 0合作 1已退出
              isInvitedAgain: el.isInvitedAgain,

              businessId: el.businessId,
              businessName: el.businessName,
              joinBusinessId: el.joinBusinessId
            }
            tableData.push(dataItem)
          })
          this.tableData = tableData
          console.log('this.tableData', this.tableData)
        }
      })
    },
    // 修改折扣佣金
    changeDisRak() {
      const { id } = this.rowConten
      const form = {
        discount: this.preferInput,
        id,
        rakeRate: this.mokeInput
      }
      modifyDiscountAndRakeRate(form).then((res) => {
        console.log('修改折扣佣金', res)
        if (res.code == 0) {
          this.$message({
            type: 'success',
            message: '修改成功!'
          })
          this.cooperationFun()
        }
      })
    },
    // 取消合作
    cancelCooperationFun() {
      const { id } = this.rowConten
      const form = {
        id
      }
      console.log(form)
      cancelCooperation(form).then((res) => {
        console.log('取消合作', res)
        if (res.code == 0) {
          this.$message({
            type: 'success',
            message: '取消成功!'
          })
          this.cooperationFun()
        }
      })
    },
    // 邀请商户
    getAddBusinessToMemberFun() {
      this.loading = true
      this.getTimeFun()
      const { mobilePhone, deptId } = this.userInfo
      const { id, fullName, name } = this.userInfo.business
      // 整理数据
      const selectMerch = [this.rowConten]
      const merchInvites = []
      selectMerch.forEach((el) => {
        console.log(el)
        const merchItem = {
          businessId: id,
          businessName: name,
          mobilePhone,
          address: fullName,

          joinBusinessId: el.id,
          joinBusinessName: el.merchName,
          joinMobilePhone: el.merchPhone,
          joinAddress: el.address,
          discount: el.discount,
          rakeRate: el.commission,
          afterDiscount: null,
          afterRakeRate: null,
          status: '0',
          isCooperate: 1,
          exitType: '0',
          remark: `【${name}】商家邀请【${el.merchName}】商家加入超级会员`,
          inviteTime: this.time,
          createTime: this.time,
          updateTime: this.time,
          confirmTime: null
        }
        merchInvites.push(merchItem)
      })
      const businessInviteRecordVo = {
        businessId: id,
        businessName: name,
        mobilePhone,
        address: fullName,
        invites: merchInvites,
        deptId: deptId
      }
      addBusinessToMember(businessInviteRecordVo).then((res) => {
        // console.log('邀请商户：', res)
        if (res.data) {
          this.loading = false
          this.$alert('邀请已经发送，请耐心等待商户处理。', '提示', {
            confirmButtonText: '确定',
            callback: (action) => {
              this.$router.push({
                name: 'MarketingActivitySuperInviterMsg'
              })
            }
          })
        } else {
          this.loading = false
        }
      })
    },
    // 获取当前时间
    getTimeFun() {
      const yy = new Date().getFullYear()
      const mm = new Date().getMonth() + 1
      const dd = new Date().getDate()
      const hh = new Date().getHours()
      const mf =
        new Date().getMinutes() < 10
          ? '0' + new Date().getMinutes()
          : new Date().getMinutes()
      const ss =
        new Date().getSeconds() < 10
          ? '0' + new Date().getSeconds()
          : new Date().getSeconds()
      this.time = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss
    }
  }
}
</script>

<style lang="scss" scoped>
.head_box {
  width: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  .tipBox {
    background-color: white;
    overflow: hidden;
    padding: 20px;
    font-size: 15px;
    margin-top: 8px;
    p {
      float: left;
      strong {
        color: red;
      }
    }
    span {
      float: left;
      color: $primary;
      cursor: pointer;
      margin-left: 16px;
    }
  }
}
.inquire_box {
  width: 100%;
  overflow: hidden;
  margin-top: 20px;
  padding: 20px;
  background-color: white;
  .status_list {
    width: 100%;
    overflow: hidden;
    .li {
      float: left;
      margin: 8px;
      margin-right: 30px;
      cursor: pointer;
    }
  }

  .serch_box {
    width: 100%;
    overflow: hidden;
    margin-top: 20px;
    .el-input,
    .el-select {
      width: 250px;
      float: left;
      margin-right: 20px;
    }
  }
}
.tipRule {
  padding: 20px;
  box-sizing: border-box;
  border-radius: 5px 5px 0 0;
  background-color: #fff;
}
.table_box {
  width: 100%;
  overflow: hidden;
  padding: 20px;
  background-color: white;
}

/deep/.changeDialog {
  .el-dialog__headerbtn {
    display: none;
  }
  .inpLis {
    margin-bottom: 8px;
    text-align: center;
    .el-input {
      width: 100px;
      text-align: center;
      input {
        text-align: center;
      }
    }
  }
}
</style>
